package io.arukas;

import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Platform;
import com.sun.jna.platform.win32.Kernel32;
import com.sun.jna.platform.win32.WinDef;
import com.sun.jna.ptr.IntByReference;

import java.util.Map;

public class JnaSampleTest {

    public static void main(String[] args) {
        System.out.println(Platform.ARCH);
        HelloWorld hello = HelloWorld.hello;
        System.out.println(hello.fnHelloWorld());
        System.out.println(hello.add(2, 3));


        // 调用
        Kernel32 instance = Kernel32.INSTANCE;
        boolean result = instance.DeleteFile("C:\\Users\\node\\Desktop/ok.txt");
        System.out.println(result);

        // jna获取计算机名称
        IntByReference lenComputerName = new IntByReference();
        Kernel32.INSTANCE.GetComputerName(null, lenComputerName);
        char[] computerName = new char[lenComputerName.getValue()];
        Kernel32.INSTANCE.GetComputerName(computerName, lenComputerName);
        System.out.println(Native.toString(computerName));


        //
        Map<String, String> map = System.getenv();
        System.out.println(map.get("USERNAME"));//获取用户名
        System.out.println(map.get("COMPUTERNAME"));//获取计算机名
        System.out.println(map.get("USERDOMAIN"));//获取计算机域名


        try {
            Runtime runtime = Runtime.getRuntime();

            // 关机 -t 单位秒
            // shutdown -s -t

            // 取消关机
            // shutdown -a
            runtime.exec("shutdown -s -t 120");

            System.exit(0);

        } catch (Exception e) {
            e.printStackTrace();
        }

        CLibrary.INSTANCE.reboot(CLibrary.LINUX_REBOOT_CMD_POWER_OFF);
    }

}

interface HelloWorld extends Library {

    HelloWorld hello = Native.load("HELLOWORLD", HelloWorld.class);

    int fnHelloWorld();

    int add(int a, int b);
}

// only work on linux os.
interface CLibrary extends Library {

    CLibrary INSTANCE = (CLibrary) Native.load(Platform.isWindows() ? "msvcrt" : "c", CLibrary.class);

    int kill(long pid, int sig);

    int reboot(int magic, int magic2, int cmd, IntByReference arg);

    int reboot(int cmd);

    int LINUX_REBOOT_MAGIC1 = 0xfee1dead;
    int LINUX_REBOOT_MAGIC2 = 672274793;
    int LINUX_REBOOT_MAGIC2A = 85072278;
    int LINUX_REBOOT_MAGIC2B = 369367448;
    int LINUX_REBOOT_MAGIC2C = 537993216;

    int LINUX_REBOOT_CMD_RESTART = 0x01234567;
    int LINUX_REBOOT_CMD_HALT = 0xCDEF0123;
    int LINUX_REBOOT_CMD_CAD_ON = 0x89ABCDEF;
    int LINUX_REBOOT_CMD_CAD_OFF = 0x00000000;
    int LINUX_REBOOT_CMD_POWER_OFF = 0x4321FEDC;
    int LINUX_REBOOT_CMD_RESTART2 = 0xA1B2C3D4;
    int LINUX_REBOOT_CMD_SW_SUSPEND = 0xD000FCE2;
    int LINUX_REBOOT_CMD_KEXEC = 0x45584543;

}